/**
 * @modal: 智能策略自动执行
 */
import CommonModal from '@/components/CommonModal';
import StrategyTable from './components/StrategyTable';
import ExecuteRecord from './components/ExecuteRecord';
import AutoConfig from './components/AutoConfig';
import HeaderTips from './components/HeaderTips';
import { Button, message } from "antd";
import { useState, useEffect, useRef } from "react";
import Api from "./service";
import moment from 'moment';
import IntelligentSplittingStrategy from "../IntelligentSplittingStrategy";

//添加0处理
function addZero(val) {
	//对于本身添加了0的直接返回原值
	val = val + '';
	if(val.startsWith('0')) {
		if(val == '0') {
			return '00';
		} else {
			return val;
		}
	}
	if (val) {
		if (val > 9) {
			return val;
		}
		return '0' + val;
	}
	return val;
}

function ManualExecute(props) {

	const { searchForm, handleOk, handleCancel, operationPage, selectKeys, orderList } = props;

	const [isOk, setIsOk] = useState(false);

	const [open, setOpen] = useState(false);

	//控制弹框组件
	const [compOpen, setCompOpen] = useState(null);

	const formRef = useRef(null);

	//当前是否更改过数据
	const [hasEdit, setHasEdit] = useState(false);

	//策略列表
	const [strategyData, setStrategyData] = useState({ smartStrategyConfigs: [] });

	useEffect(() => {
		setOpen(true);
		getStrategyList();
	}, []);

	//获取策略列表
	const getStrategyList = async () => {
		START_LOADING();
		const { success, data } = await Api.getStrategyList({
			type: 1
		});
		if (success) {
			setStrategyData(data);
		}
		END_LOADING();
	};

	//点击保存
	const handleSaveStrategy = () => {
		formRef?.current.validateFields().then(value => {
			saveStrategy(value);
		}).catch(err => console.log(err))
	}

	//保存策略
	const saveStrategy = async (formData) => {
		const params = {
			...strategyData,
			timeType: formData.timeType,
			enableAuto: formData.enableAuto ? 1 : 0,
			validityDateType: formData.validityDateType
		}
		//指定时间
		if (params.validityDateType == 2) {
			params.validityStartDate = moment(formData.validityDate[0]).format('YYYY-MM-DD');
			params.validityEndDate = moment(formData.validityDate[1]).format('YYYY-MM-DD');
		}

		//定时执行
		if (params.timeType == 1) {
			params.timeStart = addZero(formData.timeStartHour) + ':' + addZero(formData.timeStartMinutes) + ':00';
			params.timeEnd = addZero(formData.timeEndHour) + ':' + addZero(formData.timeEndMinutes) + ':00';
			params.timeInterval = formData.timeInterval;
		}
		//指定时间执行
		if (params.timeType == 2) {
			params.timePoint = formData.timePoint;
		}
		START_LOADING();
		const { success } = await Api.updateStrategyList(params);
		END_LOADING();
		if (success) {
			setIsOk(true);
			setOpen(false);
			if(params.enableAuto) {
				message.success('保存成功,当前时间会自动执行一次');
			} else {
				message.success('保存成功');
			}
		}
	}

	const onCancel = () => {
		setOpen(false);
	};

	const afterClose = () => {
		if (isOk) {
			handleOk(2);
		} else {
			handleCancel();
		}
	};

	//自动策略配置
	const AutoConfigProps = {
		formRef,
		strategyData,
	}

	//策略列表
	const StrategyTableProps = {
		type: 1,
		strategyData: strategyData,
		saveData(val) {
			const obj = { ...strategyData };
			obj.smartStrategyConfigs = val;
			setStrategyData(obj);
			//标记更改
			!hasEdit && setHasEdit(true);
		},
        handleOpenModal() { //打开只能拆单弹窗
			setCompOpen('IntelligentSplittingStrategey');
        }
	}

	//执行记录
	const ExecuteRecordProps = {
		type: 1,
		handleCancel() {
			setCompOpen(null);
		}
	}

	const modalFooter = (
		<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
			<div>
				<Button onClick={() => setCompOpen('executeRecord')} type="link">执行记录</Button>
			</div>
			<div>
				<Button onClick={onCancel}>取消</Button>
				<Button onClick={handleSaveStrategy} type="primary">保存</Button>
			</div>
		</div>
	);

        //智能拆分策略
        const IntelligentSplittingStrategyProps = {
            item: { scene: "autoSplitOrder"},
            searchForm,
            operationPage,
            selectKeys,
            orderList,
            handleCancel() {
                setCompOpen(null);
            },
            handleOk(updateType, data) {
                setCompOpen(null);
            },
        }

	return (
		<CommonModal
			title="智能策略自动执行"
			footer={modalFooter}
			afterClose={afterClose}
			open={open}
			width="762px"
			onCancel={onCancel}
		>
			<div style={{ paddingBottom: '12px' }}>
				<HeaderTips type="autoExecute" />
				<AutoConfig {...AutoConfigProps} />
				<h3 style={{ margin: '12px 0' }}>3、规则设置（拖动顺序可更换执行）</h3>
				{Object.keys(strategyData).length > 1 && <StrategyTable {...StrategyTableProps} />}
			</div>
			{compOpen == 'executeRecord' && <ExecuteRecord {...ExecuteRecordProps} />}
			{compOpen == 'IntelligentSplittingStrategey' && <IntelligentSplittingStrategy {...IntelligentSplittingStrategyProps} />}
		</CommonModal>
	);
}

export default ManualExecute;
